package com.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;

import com.util.Message;
import com.websocket.Constants;

public class ShiroOperate {
	
	/**
	 * 登入验证
	 * @param token
	 * @param code 验证码,可以为空
	 * @return
	 */
	public static Message authentication(UsernamePasswordToken token, String code) {

		// 匹配验证码
		if (code != null) {
			String rand = (String) SecurityUtils.getSubject().getSession().getAttribute("rand");
			if (!rand.toLowerCase().equals(code)) {
				return new Message("error code");
			}
		}

		try {
			SecurityUtils.getSubject().login(token);
			// 将用户名存入session中，给websocket使用
			String username = (String) token.getPrincipal();
			SecurityUtils.getSubject().getSession().setAttribute(Constants.SESSION_USERNAME, username);
			return new Message("login success");
		} catch (UnknownAccountException uae) {
			return new Message("error username");
		} catch (IncorrectCredentialsException ice) {
			return new Message("error password");
		} catch (LockedAccountException lae) {
			return new Message("locked user");
		} catch (ExcessiveAttemptsException e) {
			return new Message("locked 10min");
		}
	}
	
	/**
	 * 退出操作
	 */
	public static void logout(){
		SecurityUtils.getSubject().logout();
	}
}
